package leetcode.array;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author mazouri
 * @create 2021-05-02 23:31
 */
public class FourSum {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> lists = new ArrayList<>();
        if(nums==null||nums.length<4){
            return lists;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {

            if (i > 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < nums.length; j++) {
                int left = j + 1;
                int right = nums.length - 1;
                // j必须运行一次
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;

                while (left < right) {
                    int expectNum = target - nums[i] - nums[j];

                    if (expectNum == nums[left] + nums[right]) {
                        lists.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        while (left < right && nums[left] == nums[++left]) ;
                        while (left < right && nums[right] == nums[--right]) ;
                    } else if (nums[left] + nums[right] > expectNum) {
                        right--;
                    } else {
                        left++;
                    }
                }
            }
        }
        return lists;
    }

    @Test
    public void test() {
        int[] nums = {2, 2, 2, 2,2};
        List<List<Integer>> lists = fourSum(nums, 8);
        System.out.println(lists);
    }
}
